<template>
	<view class="content bg_com">
		<!-- 顶部 -->
		<com-nav-bar class="nav_login" :navColor="navColor">
			<template>
				<view class="_nav" @click="navBack">
					<i class="iconfont icon-31fanhui1"></i>
				</view>
			</template>
		</com-nav-bar>
		<view class="bg_warp">
			<image class="img_val" src="../../static/login_bg.png" mode="scaleToFill"></image>
		</view>
		<view class="login_warp">
			<view class="login_logo">
				<view class="icon">
					<image class="img_val" src="../../static/logo.jpg" mode="scaleToFill"></image>
				</view>
				<view class="msg">
					登录后体验完成功能
				</view>
			</view>

			<view v-if="loginType == 'mp'" class="wx_login_btn">
				<button class="wx_btn" type="default" v-if="!isBind" open-type="getPhoneNumber"
					@getphonenumber="onGetPhoneNumber">
					<image class="wx_img" src="../../static/wx_2x.png" mode="scaleToFill"></image>
					微信一键登录
				</button>
			</view>
			<view v-else-if="loginType == 'mobile'" class="wx_login_btn">
				<button class="wx_btn" type="default" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
					<image class="wx_img" src="../../static/wx_2x.png" mode="scaleToFill"></image>
					手机号快速登录
				</button>
			</view>
			<view v-else-if="loginType == 'account'" class="phone_login col_conter">
				<input class="input_warp" v-model="phone" @input="watchIng" type="number" placeholder="请输入手机号/ID" />
				<input class="input_warp bot" v-model="password" @input="watchIng" type="password"
					placeholder="请输入密码" />
				<view class="btn_warp" @click="phoneLogin">
					<image class="img_val" v-if="!isDian" src="../../static/login_btn_disable.png" mode="scaleToFill">
					</image>
					<image class="img_val" v-else src="../../static/login_btn.png" mode="scaleToFill"></image>
				</view>
			</view>
		</view>
		<!-- 底部 -->
		<view class="bottom">
			<view class="msg">
				- 其他方式登录 -
			</view>
			<view class="icon_warp row_center">
				<image class="icon" @click="loginType = 'account'" src="../../static/phone_dl.png" mode="scaleToFill">
				</image>
				<image class="icon right" @click="loginType = 'mp'" src="../../static/wx_dl.png"
					mode="scaleToFill">
				</image>
			</view>
			<view class="protocol">
				登录/注册即代表阅读 <text class="shu">《用户协议》</text>和<text class="shu">《隐私政策》</text>
			</view>
		</view>
		<!-- 弹窗 -->
		<uni-popup ref="popup" type="center">
			<view class="modal_warp col_conter">
				<view class="title">
					完善个人信息
				</view>
				<view class="msg row_center">
					首次登录需要获取用户信息用于注册
				</view>
				<view class="btn_warp row_center">
					<view class="btn cancel" @click="cancel">
						取消
					</view>
					<view class="btn confirm" @click="getUserProfile">
						确定
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import {
		des_encrypt,
		desAndBase
	} from '@/common/encryption.js';

	var timer = null;
	export default {
		computed: mapState(['identity']),
		data() {
			return {
				uid: -1,
				isBind: false,
				isDian: false,
				navColor: 'transparent',
				isMobile: false, // 是否为手机号登录
				loginType: 'mp',
				phone: '', // 2146354 2356327
				password: '',
				client_id: 'wanpi-client',
				username: '',
				tickForm: {},
				idData: null,
				code: ''
			}
		},
		onUnload() {
			if (timer) clearTimeout(timer);
		},
		onShow() {
			this.getCode();
		},
		onLoad() {

		},
		methods: {
			...mapActions(['login', 'setUserInfo', 'LogOut', 'GetTicket']),
			navBack() {
				console.log("进来了")
				uni.navigateBack()
			},
			getCode() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log(loginRes);
						this.code = loginRes.code;
					},
				});
			},
			/* 监听是否输入了账号和密码 */
			watchIng() {
				if (this.phone !== '' && this.password !== '') {
					this.isDian = true;
				} else {
					this.isDian = false;
				}
			},
			/* 获取用户信息 */
			getUser(uid) {
				return new Promise((res) => {
					this.$api.getUser({
						uid
					}).then(result => {
						res(result);
					})
				})
			},
			/* 登录成功跳转主页 */
			jumpHome() {
				timer = setTimeout(() => {
					uni.hideLoading();
					uni.showToast({
						title: '登录成功'
					});
					uni.switchTab({
						url: '../tabBar/index/index'
					})
				}, 1000)
			},
			/* 获取ticket */
			getTicketFun() {
				this.$api.getTicket(this.tickForm).then(async (res) => {
					if (res.code + '' === '200') {
						this.GetTicket(res.data.tickets);
						if (this.loginType == 'mp') {
							this.uid = res.data.uid;
							let userRes = await this.getUser(res.data.uid);
							if (!userRes.data.uid) {
								uni.hideLoading();
								this.$refs.popup.open();
							} else {
								this.login(this.idData);
								this.setUserInfo(userRes.data);
								this.jumpHome();
							}
							return;
						} else {
							this.jumpHome();
						}
					} else {
						this.LogOut();
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
				})
			},
			/* 获取设备信息 */
			getDevInfo(token) {
				this.tickForm = {
					access_token: token
				}
				this.getTicketFun();
				return;
				/* 暂时弃用》》》》》》》》》》》》》》》》》》》》》》》》》》》 */
				/* var _this = this;
				let netType = '';
				uni.getNetworkType({
					success: function(res) {
						netType = res.networkType
						uni.getSystemInfo({
							success: function(res) {
								let appVersion = '1.0.0';
								// #ifdef MP-WEIXIN
								let ver = wx.getAccountInfoSync();
								appVersion = (ver.miniProgram.version != '') ? ver.miniProgram
									.version : '1.0.0';
								console.log(appVersion)
								// #endif
								_this.tickForm = {
									issue_type: 'multi', //
									access_token: token,
									os: res.platform,
									app: 'wanpi',
									model: res.model, // 手机机型
									channel: 'official_mini1', // 渠道码
									deviceId: res.deviceId, // 手机设备ID
									appVersion: appVersion, // 小程序版本号
									osVersion: res.system, // 手机系统版本
									netType: netType, //网络类型
									ispType: utils.checkMobile('15371619859'), //运营商类型
									pub_timestamp: new Date().getTime(),
									pub_sign: '',
									appVersion: appVersion
								}
								_this.getTicketFun();
								console.log(_this.tickForm)
							},
							fail(err) {
								uni.showToast({
									title: '意外错误',
									icon: 'error'
								});
							}
						});
					},
					fail(err) {
						uni.showToast({
							title: '意外错误',
							icon: 'error'
						});
					}
				}); */
			},
			/* 手机号登录 */
            phoneLoginDo(openId) {
				this.$api.loginDo({
					phone: this.phone,
					client_id: this.client_id,
					username: this.username,
					password: des_encrypt(this.password),
					grant_type: 'password',
					client_secret: 'uyzjdhds'
				}).then(async (res) => {
					console.log(res);
					if (res.code + '' === '200') {
						console.log(res.data);
						let resultData = res.data;
						resultData.openId = openId;
						this.login(resultData);
						let userRes = await this.getUser(res.data.uid);
						this.setUserInfo(userRes.data);
						this.getDevInfo(res.data.access_token);
					} else {
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
				})
			},
			/* 手机号登录 */
			phoneLogin() {
				if (this.phone == '') {
					uni.showToast({
						title: '请输入手机号',
						icon: 'error'
					});
					return;
				}
				if (this.password == '') {
					uni.showToast({
						title: '请输入密码',
						icon: 'error'
					});
					return;
				}
				uni.showLoading({
					title: '登录中...'
				})
				this.$api.getOpenId({
					jsCode: this.code
				}).then(res => {
					if (res.code == 200) {
						this.phoneLoginDo(res.data.openId);
					}else {
						uni.hideLoading();
						uni.showToast({
							title: '意外错误',
							icon: 'error'
						});
					}
				})
				
			},
			/* 微信登录 */
			wxLoginDo(openId, encryptedData, iv) {
				uni.showLoading({
					title: '登录中...'
				})
				this.$api.loginDo({
					/* phone: this.phone, */
					openId,
					encryptedData,
					iv,
					client_id: this.client_id,
					grant_type: 'mini_app',
					client_secret: 'uyzjdhds',
					type: 8,
				}).then(async (res) => {
					console.log(res);
					if (res.code + '' === '200') {
						this.idData = res.data;
						this.getDevInfo(res.data.access_token);
					} else {
						uni.hideLoading();
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
				})
			},
			/* 注册用户 */
			setUserFun(avatar, nick) {
				uni.showLoading({
					title: '请稍后...'
				})
				this.$api.setUser({
					avatar,
					nick,
					uid: this.uid
				}).then(async (res) => {
					uni.hideLoading();
					if (res.code == 200) {
						let userRes = await this.getUser(this.uid);
						this.login(this.idData);
						this.setUserInfo(userRes.data);
						this.jumpHome();
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			cancel() {
				this.closePopup();
				this.getCode();// 重新获取code
			},
			closePopup() {
				this.$refs.popup.close();
			},
			/* 获取用户信息 */
			getUserProfile() {
				let _this = this;
				this.closePopup();
				uni.getUserProfile({
					desc: "用于完善会员资料",
					success: (res) => {
						uni.setStorageSync('isCanUse', false); //记录是否第一次授权  false:表示不是第一次授权
						let nickName = res.userInfo.nickName; //昵称
						let avatar = res.userInfo.avatarUrl; //头像
						this.setUserFun(avatar, nickName);
					},fail(err) {
						console.log(err);
						_this.getCode();// 重新获取code
					}
				})
			},
			/* 获取手机号登录 */
			onGetPhoneNumber(e) {
				console.log(e)
				if (e.detail.encryptedData) {
					this.$api.getOpenId({
						jsCode: this.code
					}).then(res => {
						if (res.code == 200) {
							this.wxLoginDo(res.data.openId, e.detail.encryptedData, e.detail.iv);
						}
					})
				}
			},
			/* 微信登录 */
			wxLoginFun(nickName) {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log(loginRes);
						let code = loginRes.code;
						this.isBind = true;
						this.getOpenId(code, nickName);
					},
				});

			}

		}
	}
</script>

<style lang="scss">
	@import "@/static/iconfont/iconfont.css";

	@font-face {
		font-family: 'iconfont';
		src: url('~@/static/iconfont/iconfont.ttf');
	}

	@import './index.scss';
</style>
